#!/usr/bin/env python
#
#   Copyright (C) 2006 Jonathan Saggau
#   saggau@gmail.com      
#   Some code from AthenaCL by Chris Ariza (GPL)                                                                                    
#                                                                          
#   This program is free software; you can redistribute it and/or modify  
#   it under the terms of the GNU General Public License as published by  
#   the Free Software Foundation; either version 2 of the License, or     
#   (at your option) any later version.                                    
#                                                                          
#   This program is distributed in the hope that it will be useful,        
#   but WITHOUT ANY WARRANTY; without even the implied warranty of        
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         
#   GNU General Public License for more details.                          
#                                                                          
#   You should have received a copy of the GNU General Public License     
#   along with this program; if not, write to the                         
#   Free Software Foundation, Inc.,                                        
#   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.  
#

from Foundation import *
from AppKit import *

import os, time
SOUNDFILE_TYPES = (".aif", ".aiff", ".wav")
        
def extSplit(name, extList=None):
   """split name, extension; if extList is given, find only w/n this list
   return wholeName (even if a path), None if ext not found
   all '.' are dropped from both name and ext
   """
   if extList == None:
      extList = SOUNDFILE_TYPES # search all known extensions
   nameStub = name
   foundExt = ''
   for ext in extList:
      if name[-len(ext):].lower() == ext: # if has this ext
         nameStub = name[:-len(ext)]
         foundExt = ext
         break
   if nameStub == name: # no extension foudn
      return nameStub, None
   else: # check for periods, extension should have leading period
      if nameStub[-1] == '.':
         nameStub = nameStub[:-1]
      if foundExt[0] != '.': # start with leading period
         foundExt = '.' + foundExt
      return nameStub, foundExt

def findAudioFiles(dir, path = None, recursive = False, 
                   extensions = SOUNDFILE_TYPES):
   """find all audio files in path; if extensions (list)  is given, 
      look only for the specific extensions in list, otherwise use
      the extensions in SOUND_FILE_TYPES"""
   if not extensions:
       extensions = SOUND_FILE_TYPES
   audioFiles = []
   if recursive:
      for root, dirs, files in os.walk(dir):
         for eachFile in files:
            name, ext = extSplit(eachFile)
            if ext in extensions:
               foundFilePath = os.path.join(root, eachFile)
               audioFiles.append(foundFilePath)
   else:
      for eachFile in os.listdir(path):
         name, ext = extSplit(eachFile)
         if ext in extensions:
            foundFilePath = os.path.join(path, eachFile)
            audioFiles.append(foundFilePath)
   return audioFiles
   
def openPanelFindAudioFiles(recursive = False, extensions = SOUNDFILE_TYPES):
    """Opens an NSOpenPanel to choose the directory to search"""
    panel = NSOpenPanel.openPanel()
    panel.setAllowsMultipleSelection_(False)
    panel.setCanChooseDirectories_(True)
    panel.setCanChooseFiles_(False)
    rval = panel.runModalForDirectory_file_types_(None, None, None)
    path = panel.filenames()[0]
    NSLog("PATH = %s" %(path,))
    soundFiles = findAudioFiles(path, recursive, extensions)
    return (path, soundFiles)